package com.wonderful.compose

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.wonderful.compose.anim.AnimActivity
import com.wonderful.compose.blur.BlurViewActivity
import com.wonderful.compose.booking.BookingActivity
import com.wonderful.compose.channel.ChannelDemo01Activity
import com.wonderful.compose.clock.ClockActivity
import com.wonderful.compose.lazy.LazyLayoutActivity
import com.wonderful.compose.navigation.UseNavigationNavActivity
import com.wonderful.compose.navigation.UseStateNavActivity
import com.wonderful.compose.overlap.OverlappingActivity
import com.wonderful.compose.progress.FlyProgressActivity
import com.wonderful.compose.resize.AvoidResizeActivity
import com.wonderful.compose.scroll.NestedScrollActivity
import com.wonderful.compose.side_effect.SideEffectActivity
import com.wonderful.compose.ui.theme.ComposeLearnTheme
import kotlin.math.roundToInt

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeLearnTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    //Greeting("Android")
                    //SimpleWidgetColumn()
                    //IconImage()
                    //PointerInputEvent()
                    //HighLevelCompose()
                    Column(
                        modifier = Modifier.verticalScroll(rememberScrollState()),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, ClockActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "Clock Activity")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, LazyLayoutActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "Lazy Layout")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, BookingActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "Booking")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, BlurViewActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "Blur")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, AvoidResizeActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "Resize")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, NestedScrollActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "Nested scroll")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, OverlappingActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "Overlap list")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, FlyProgressActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "Fly Progress")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent =
                                Intent(this@MainActivity, ChannelDemo01Activity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "Channel demo 01")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, AnimActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "动画")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, SideEffectActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "side effect")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, UseStateNavActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "state nav")
                        }

                        Button(modifier = Modifier.padding(0.dp, 10.dp), onClick = {
                            val intent = Intent(this@MainActivity, UseNavigationNavActivity::class.java)
                            startActivity(intent)
                        }) {
                            Text(text = "navigation")
                        }
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        val packageInfo = applicationContext.packageManager
            .getPackageInfo(applicationContext.packageName, 0)
        Log.wtf("wonderful", "versionName = ${packageInfo.versionName}")
        Log.wtf("wonderful", "versionCode = ${packageInfo.versionCode}")
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    Text(
        text = "Hello $name!",
        modifier = modifier
    )
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    ComposeLearnTheme {
        Greeting("Android")
    }
}

// -------------------------------------- Basic ---------------------------------------

@OptIn(ExperimentalMaterial3Api::class)
@Preview(showBackground = true)
@Composable
fun SimpleWidgetColumn() {

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState()),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.SpaceEvenly
    ) {
        val context = LocalContext.current
        Text(
            modifier = Modifier.align(Alignment.End),
            text = "this is a simple widget",
            color = Color.Cyan,
            fontSize = 22.sp
        )
        Button(onClick = {
            Toast.makeText(context, "click", Toast.LENGTH_SHORT).show()
        }) {
            Text(
                text = "This is a Button",
                color = Color.White,
                fontSize = 22.sp
            )
        }
        // 类似EditText
        TextField(
            value = "",
            onValueChange = {},
            placeholder = {
                Text(text = "This is a TextField")
            },
            colors = TextFieldDefaults.colors()
        )

        Image(
            painter = painterResource(id = R.drawable.prince_christian_sound),
            contentDescription = "Prince Christian Sound"
        )
//        val bitmap: ImageBitmap = ImageBitmap.imageResource(id = R.drawable.prince_christian_sound)
//        Image(
//            bitmap = bitmap,
//            contentDescription = "Prince Christian Sound"
//        )
//        val traditionalBitmap: Bitmap =
//            BitmapFactory.decodeResource(context.resources, R.drawable.prince_christian_sound)
//        Image(bitmap = traditionalBitmap.asImageBitmap(), contentDescription = "")

        // coil 加载网络图片
        AsyncImage(
            model = "https://img-blog.csdnimg.cn/20200401094829557.jpg",
            contentDescription = "coil load test"
        )

        CircularProgressIndicator(
            color = Color.Green,
            strokeWidth = 6.dp
        )

        LinearProgressIndicator(
            color = Color.Blue,
            trackColor = Color.Green
        )

        Box(modifier = Modifier.fillMaxSize()) {
            Text(modifier = Modifier.align(Alignment.TopStart), text = "top start")
            Button(onClick = { /*TODO*/ }, modifier = Modifier.align(Alignment.TopEnd)) {
                Text(text = "top end")
            }
        }
    }
}

// -------------------------------------- Modifier ---------------------------------------


/**
 * Modifier 主要负责以下4个大类的功能
 *
 * 修改Compose控件的尺寸、布局、行为和样式。
 * 为Compose控件增加额外的信息，如无障碍标签。 -- 如Accessibility的最主要目的，是结合Talkback为那些有视觉障碍的群体提供发音辅助的，以保证即使他们的眼睛看不见或看不清，也可以正常地使用手机和各类App。
 * 处理用户的输入
 * 添加上层交互功能，如让控件变得可点击、可滚动、可拖拽。
 */

/**
 * Modifier -- 修改Compose控件的尺寸、布局、行为和样式
 *
 * tip：当需要修改Compose控件外观的时候，找Modifier就对了。
 *
 * Modifier 的串接顺序有影响
 *
 * tip：在Compose当中根本就没有layout_marge这个属性所对应的概念，需要调整一下padding()函数的调用顺序即可
 */
@Composable
fun IconImage() {
    Image(
        painter = painterResource(id = R.drawable.prince_christian_sound),
        contentDescription = "icon image",
        modifier = Modifier
            .wrapContentSize(align = Alignment.CenterStart) // 图片垂直居中水平居左对齐
            .background(Color.Green)
            .padding(20.dp)
            .border(5.dp, Color.Magenta, CircleShape) // 增加边框
            .padding(20.dp)
            .clip(CircleShape)  // 裁剪
        //.rotate(180f) // 旋转180
    )
}

/**
 * Modifier -- 处理用户的输入
 *
 * 这里的用户输入并不是指的文本输入框的输入，那个是由TextField控件处理的，和Modifier关系不大
 *
 * 这里的用户输入指的是，当用户的手指在屏幕上进行滑动、点击各种操作时，会认为这是用户的一种输入，而我们则需要对这类输入进行处理。
 */
@Composable
fun PointerInputEvent() {
    var offsetX by remember { mutableStateOf(0f) }
    var offsetY by remember { mutableStateOf(0f) }
    // Compose中的Box基本就相当于View中的FrameLayout
    Box(
        modifier = Modifier
            .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
            .requiredSize(200.dp)
            .background(Color.Yellow)
            .pointerInput(Unit) {// pointerInput()函数至少要传入一个参数，这个参数的作用是，当参数的值发生变化时，pointerInput()函数会重新执行，而如果你并没有需求需要pointerInput()函数重新执行，那么传入一个Unit参数就可以了。

                // 底层写法
                awaitPointerEventScope {
                    while (true) {
                        val event = awaitPointerEvent()
                        Log.e("PointerInputEvent", "event：${event.type}")
                    }
                }
            }
            .pointerInput(Unit) {
                // Compose 提供的好用API: 监听用户的点击事件
                detectTapGestures {
                    Log.d("PointerInputEvent", "Tap")
                }
                // Never reach
            }
            .pointerInput(Unit) {
                // Compose 提供的好用API: 监听用户的拖拽事件
                detectDragGestures { change, dragAmount ->
                    Log.d("PointerInputEvent", "Dragging")
                    change.consume() //事件处理完了，要记得调用consume()函数将它消费掉
                    offsetX += dragAmount.x
                    offsetY += dragAmount.y
                }
                // Never reach
            }
    )
}

/**
 * Modifier -- 使控件可点击、滚动、拖拽
 *
 * 总体来说，使用pointerInput()函数来处理用户输入是比较偏底层的，就像是在View系统中处理TouchEvent一样。
 *
 * Modifier提供了足够多的上层API来处理诸如点击、滚动、拖拽等用户输入事件。
 */
@Composable
fun HighLevelCompose() {
    val context = LocalContext.current
    var offsetX by remember { mutableStateOf(0f) }
    Column(
        modifier = Modifier
            .offset { IntOffset(offsetX.roundToInt(), 0) }
            .requiredSize(200.dp)
            .background(Color.Cyan)
            .verticalScroll(rememberScrollState()) // 滚动
            .draggable( // draggable()函数允许让一个控件在水平或垂直方向上拖拽，并可以监听用户的拖拽距离，但不可以同时在水平和垂直方向上拖拽，若有这种需求可参考pointerInput()函数来实现
                orientation = Orientation.Horizontal,
                state = rememberDraggableState { delta ->
                    offsetX += delta
                }
            )
    ) {
        Box(
            modifier = Modifier
                .requiredSize(50.dp)
                .background(Color.Green)
                .clickable { // Box 默认不点击，用 clickable()函数 即可
                    Toast
                        .makeText(context, "Box is clicked", Toast.LENGTH_SHORT)
                        .show()
                }
        )

        repeat(10) {
            Text(text = "item $it", color = Color.White, fontSize = 26.sp)
        }
    }
}